//package com.navinfo.collect.activity
//
//import android.annotation.SuppressLint
//import android.app.Activity
//import android.content.DialogInterface
//import android.content.Intent
//import android.os.Build
//import android.os.Bundle
//import android.os.Message
//import android.util.Log
//import android.view.View
//import android.view.ViewGroup
//import android.view.animation.AlphaAnimation
//import android.view.animation.Animation
//import android.view.animation.AnimationSet
//import android.view.animation.ScaleAnimation
//import android.widget.Button
//import android.widget.LinearLayout
//import android.widget.Toast
//import android.widget.*
//import androidx.annotation.RequiresApi
//import androidx.core.view.get
//import androidx.core.widget.NestedScrollView
//import com.google.android.material.bottomsheet.BottomSheetBehavior
//import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
//import com.google.android.material.card.MaterialCardView
//import com.google.android.material.dialog.MaterialAlertDialogBuilder
//import com.google.android.material.floatingactionbutton.FloatingActionButton
//import com.google.android.material.internal.ViewUtils
//import com.hjq.permissions.OnPermissionCallback
//import com.hjq.permissions.Permission
//import com.hjq.permissions.XXPermissions
//import com.navinfo.collect.R
//import com.navinfo.collect.adapter.NewDataAdapter
//import com.navinfo.collect.fragment.NIFragmentManager
//import com.navinfo.collect.library.data.NavinfoPbfData
//import com.navinfo.collect.library.map.MapManager
//import com.navinfo.collect.library.map.NIMapView
//import com.squareup.moshi.Moshi
//import me.rosuh.filepicker.config.FilePickerManager
//import org.oscim.layers.vector.VectorLayer
//import java.io.File
//import java.io.FileInputStream
//
//
//class MainActivity : BaseActivity() {
//    private var screenHeight = 0
//    private var peekHeight = 0
//    private val bottomSheet: NestedScrollView by lazy { findViewById(R.id.bottom_sheet) };
//    private val bottomSheetBehavior: BottomSheetBehavior<View> by lazy {
//        BottomSheetBehavior.from(
//            bottomSheet
//        )
//    }
//
//    private val mAddView: View by lazy { findViewById(R.id.activity_main_add) }
//
//    private val locationView: FloatingActionButton by lazy { findViewById(R.id.fab_my_location) }
//
//    private val fabContainer: LinearLayout by lazy { findViewById(R.id.fab_container) }
//
//    private val btnParserPbf: Button by lazy { findViewById(R.id.btn_parser_pbf) }
//
//    private val itemChipsLayout: HorizontalScrollView by lazy { findViewById(R.id.item_chips) }
//
//    private lateinit var moshi: Moshi
//
//    private lateinit var vectorLayer: VectorLayer
//
//    private val textList = arrayListOf(
//        "我的关注", "通知开关", "我的徽章", "意见反馈", "我要投稿",
//        "我的关注", "通知开关", "我的徽章", "意见反馈", "我要投稿",
//        "我的关注", "通知开关", "我的徽章", "意见反馈", "我要投稿"
//    )
//
//    private val mMapView: NIMapView by lazy { findViewById(R.id.mapview) }
//    private val adapter: NewDataAdapter by lazy { NewDataAdapter(ArrayList<String>()) }
//
//    private val cardView: MaterialCardView by lazy { findViewById(R.id.cardView) }
//
//    private val searchIView: ImageView by lazy { findViewById(R.id.searchIView) }
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        moshi = Moshi.Builder().build()
//        requestPermission()
//    }
//
//
//    /**
//     * 初始化BottomSheet
//     */
//    @SuppressLint("RestrictedApi")
//    private fun initBehavior() {
//        val dm = resources.displayMetrics
//        screenHeight = dm.heightPixels
//        peekHeight = ViewUtils.dpToPx(this, 100).toInt()
//        bottomSheetBehavior.addBottomSheetCallback(bottomSheetCallback())
//        bottomSheet.post {
//
//            //设置bottomSheet的总高度
//            val params: ViewGroup.LayoutParams = bottomSheet.getLayoutParams()
//            params.height = screenHeight
//            bottomSheet.setLayoutParams(params)
//            bottomSheetBehavior.setFitToContents(false) //展开后开度填充Parent的高度
//            //setFitToContents 为false时，展开后距离顶部的位置（Parent会以PaddingTop填充）
//            bottomSheetBehavior.setExpandedOffset(64)
//            bottomSheetBehavior.setHalfExpandedRatio(0.45f)
//            bottomSheetBehavior.setHideable(true)
//            bottomSheetBehavior.setPeekHeight(peekHeight, true)
//            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN)
//        }
//    }
//
//    private fun bottomSheetCallback(): BottomSheetCallback {
//        return object : BottomSheetCallback() {
//            override fun onStateChanged(bottomSheet: View, newState: Int) {
//                println("jingo " + newState)
//                when (newState) {
//                    BottomSheetBehavior.STATE_COLLAPSED -> if (bottomSheet.getScrollY() != 0) {
//                        bottomSheet.setScrollY(0) //列表滑动到顶端
//                    }
//                    BottomSheetBehavior.STATE_HALF_EXPANDED -> if (cardView.getTranslationY() != 0f) {
//                        cardView.setTranslationY(0f)
//                    }
//                }
//                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
//                    mAddView.visibility = View.VISIBLE
//                }
////                if (newState != BottomSheetBehavior.STATE_SETTLING) {
//                if (bottomSheet.y > fabContainer.y + fabContainer.height) {
////                        if (fabContainer.getVisibility() != View.VISIBLE) {
////                            fabContainer.setVisibility(View.VISIBLE)
////                        }
//
//                } else {
//                    if (fabContainer.getVisibility() != View.INVISIBLE) {
//                        fabContainer.setVisibility(View.INVISIBLE)
//                    }
//                }
////                }
//            }
//
//            override fun onSlide(bottomSheet: View, slideOffset: Float) {
//                val distance: Float
//                if (slideOffset > 0) { //在peekHeight位置以上 滑动(向上、向下) slideOffset bottomSheet.getHeight() 是展开后的高度的比例
//                    val height = bottomSheet.height
//                    distance = height * slideOffset
//                    //地图跟随滑动，将我的位置移动到中心
////                    aMap.moveCamera(CameraUpdateFactory.zoomTo(ZOOM))
////                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(viewModel.getMyLocation()))
////                    mapView.scrollTo(0, (-(distance / 2f)).toInt())
////                    mapView.setTranslationY(-distance)
//                    //搜索栏反向位移
//                    val halfExpandedRatio = bottomSheetBehavior.halfExpandedRatio
//                    val halfHeight = halfExpandedRatio * height //中间状态的高度
//                    if (distance > halfHeight) {
//                        cardView.setTranslationY(-(distance - halfHeight))
//                        cardView.setAlpha(1 - slideOffset + halfExpandedRatio)
////                        itemChips.getRoot().setAlpha(1 - slideOffset)
//
//                    } else {
//                        cardView.setTranslationY(0f)
//                        cardView.setAlpha(1.0f)
////                        itemChips.getRoot().setAlpha(1.0f)
//                    }
//                } else { //在peekHeight位置以下 滑动(向上、向下)  slideOffset 是PeekHeight的高度的比例
//                    distance = bottomSheetBehavior.peekHeight * slideOffset
//                }
//                if (distance < 0) {
//                    fabContainer.setTranslationY(-distance)
//                } else if (distance <= peekHeight) {
//                    //右侧按钮最大可位移高度为peekHeight
//                    fabContainer.setTranslationY(-distance)
//                } else if (distance > peekHeight) {
//
//                    var height = fabContainer.y + fabContainer.height
//                    if (bottomSheet.y >= fabContainer.y && bottomSheet.y <= height) {
//                        var top = bottomSheet.y - fabContainer.y
//                        var alpha = top / fabContainer.height
//                        fabContainer.get(0).alpha = alpha
//                        fabContainer.get(1).alpha = alpha
//                        if (fabContainer.getVisibility() != View.VISIBLE) {
//                            fabContainer.setVisibility(View.VISIBLE)
//                        }
//                    }
//                }
//            }
//        }
//    }
//
//    private fun refreshLocation(list: ArrayList<String>) {
//        adapter.notifyDataSetChanged(list)
//        refreshState(list.size)
//    }
//
//    private fun refreshState(count: Int) {
//        bottomSheetBehavior.state = BottomSheetBehavior.STATE_HALF_EXPANDED
//    }
//
//    fun initView() {
//
//        locationView.setOnClickListener { refreshLocation(textList) }
//        //增加新数据
//        mAddView.setOnClickListener {
//            val set = AnimationSet(true)
//            val scale = ScaleAnimation(
//                1f,
//                0.1f,
//                1f,
//                0.1f,
//                Animation.RELATIVE_TO_SELF,
//                0.5f,
//                Animation.RELATIVE_TO_SELF,
//                0.5f
//            )
//            scale.duration = 300
//            set.addAnimation(scale)
//            val alpha = AlphaAnimation(1f, 0f)
//            alpha.duration = 300
//            set.addAnimation(alpha)
//            set.setAnimationListener(object : Animation.AnimationListener {
//                override fun onAnimationStart(animation: Animation?) {
//
//                }
//
//                override fun onAnimationEnd(animation: Animation?) {
//                    mAddView.visibility = View.GONE
//                    NIFragmentManager.instance.menuShowNewDataMenuFragment()
//                }
//
//                override fun onAnimationRepeat(animation: Animation?) {
//
//                }
//            })
//            mAddView.startAnimation(set)
//
//        }
//
//        locationView.setOnClickListener {
//        }
//        searchIView.setOnClickListener {
//            cardView.visibility = View.VISIBLE
//            itemChipsLayout.visibility = View.VISIBLE
//        }
//
//        mMapView.setOnMapTouchListener {
//            if (cardView.visibility != View.GONE) {
//                cardView.visibility = View.GONE;
//            }
//            if (itemChipsLayout.visibility != View.GONE) {
//                itemChipsLayout.visibility = View.GONE;
//            }
//        }
//
//        btnParserPbf.setOnClickListener { selectPbfFile() }
//    }
//
//    private fun selectPbfFile() {
//        try {
//            FilePickerManager
//                .from(this)
//                .forResult(FilePickerManager.REQUEST_CODE)
//        } catch (e: Exception) {
//            Log.e("MainActivity：", e.toString())
//        }
//    }
//
//    @RequiresApi(Build.VERSION_CODES.N)
//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        when (requestCode) {
//            FilePickerManager.REQUEST_CODE -> {
//                if (resultCode == Activity.RESULT_OK) {
//                    val files = FilePickerManager.obtainData()
//                    Log.d("MainActivity：", "用户选中的文件是$files")
//                    if (files.isNullOrEmpty()) {
//
//                    } else {
//                        // 用户选中了对应的pbf数据
//                        val pbfData = NavinfoPbfData()
//                        val resultData = pbfData.readPbfData(FileInputStream(File(files.get(0))))
//                        if (resultData.hadlanelinkList.isNotEmpty()) {
//                            resultData.hadlanenodeList.get(0).geometry
//                            for (hadLaneLink in resultData.hadlanelinkList) {
////                                val jsonAdapter: JsonAdapter<Hadlanelink.HadLaneLink> = moshi.adapter(Hadlanelink.HadLaneLink::class.java)
////                                println("Geometry-Point3D:"+jsonAdapter.toJson(hadLaneLink))
//                                val result = pbfData.createGeometry(hadLaneLink.geometry)
//                                // 绘制geometry到地图
//
//                                println("Geometry:${result}")
////                                println("Geometry-properties:${result.userData}")
//                                for (entry in hadLaneLink.allFields) {
//                                    println("Geometry-properties:${entry.key.name} : ${entry.value}")
//                                }
//                            }
//                        }
//                    }
//                } else {
//                    Toast.makeText(this@MainActivity, "没有选择任何东西~", Toast.LENGTH_SHORT).show()
//                }
//            }
//        }
//    }
//
////    private fun requestPermission() {
////        if (Build.VERSION.SDK_INT >= 23) {
////            val permissions = arrayOf(
////                Manifest.permission.ACCESS_COARSE_LOCATION,
////                Manifest.permission.READ_PHONE_STATE,
////                Manifest.permission.WRITE_EXTERNAL_STORAGE,
////                Manifest.permission.WRITE_SECURE_SETTINGS,
////                Manifest.permission.WRITE_SETTINGS,
////                Manifest.permission.RECORD_AUDIO
////            )
////            if (ActivityCompat.checkSelfPermission(
////                    this,
////                    permissions[0]
////                ) != PackageManager.PERMISSION_GRANTED
////            ) {
////                ActivityCompat.requestPermissions(this, permissions, 0x99)
////            } else {
//////                supportFragmentManager.beginTransaction().add(R.id.main_fragment_layout, MainFragment::class.java, null).commit()
////            }
////        }
////    }
//
//    private fun requestPermission() {
////        @RequiresApi(Build.VERSION_CODES.R)
////        if (!Environment.isExternalStorageManager()) {
////            val managerExtensions: Intent = Intent()
////            managerExtensions.action = Manifest.permission.MANAGE_EXTERNAL_STORAGE
////        }
//        XXPermissions.with(this)
//            // 申请单个权限
//            .permission(Permission.ACCESS_COARSE_LOCATION)
//            .permission(Permission.ACCESS_FINE_LOCATION)
//            .permission(Permission.READ_EXTERNAL_STORAGE)
//            .permission(Permission.WRITE_EXTERNAL_STORAGE)
//            .permission(Permission.REQUEST_INSTALL_PACKAGES)
//            // 设置权限请求拦截器（局部设置）
//            //.interceptor(new PermissionInterceptor())
//            // 设置不触发错误检测机制（局部设置）
//            //.unchecked()
//            .request(object : OnPermissionCallback {
//
//                override fun onGranted(permissions: MutableList<String>, all: Boolean) {
//                    if (all) {
//                        Toast.makeText(this@MainActivity, "获取所有权限成功", Toast.LENGTH_SHORT).show()
//                    } else {
//                        Toast.makeText(this@MainActivity, "获取权限成功：$permissions", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//                    if (permissions.contains(Permission.READ_EXTERNAL_STORAGE)) {
//                        setContentView(R.layout.activity_main)
//                        MapManager.instance.init(mMapView)
//                        NIFragmentManager.instance.init(
//                            this@MainActivity,
//                            R.id.activity_main_menu_fragment,
//                            bottomSheetBehavior
//                        );
//                        initBehavior()
//                        initView()
//                    }
//                }
//
//                override fun onDenied(permissions: MutableList<String>, never: Boolean) {
//                    val value = if (never) {
//                        val dialogBuilder = MaterialAlertDialogBuilder(this@MainActivity)
//                            .setTitle("提醒")
//                            .setMessage("您拒绝了$permissions 等权限，点击确定在设置中手动授权！")
//                            .create()
//
//
//                        dialogBuilder.setButton(
//                            DialogInterface.BUTTON_POSITIVE,
//                            "确定",
//                            object : DialogInterface.OnClickListener {
//                                override fun onClick(p0: DialogInterface?, p1: Int) {
//                                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
//                                    XXPermissions.startPermissionActivity(
//                                        this@MainActivity,
//                                        permissions
//                                    )
//                                }
//                            })
//                        dialogBuilder.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", Message())
//                        dialogBuilder.show()
//                    } else {
//                        Toast.makeText(this@MainActivity, "拒绝授予权限：$permissions", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//                }
//            })
//    }
//}